import React from "react";
import { useRequest } from "ahooks";

const ImgSelection = () => {
  const [requestId, setRequestId] = React.useState<string | null>(null);

  // 提交操作
  const submit = async () => {
    // 假设submitAPI是一个返回requestId的异步函数
    const response = await submitAPI();
    setRequestId(response.requestId);
  };

  // 轮询操作
  const { data, run } = useRequest(
    async () => {
      if (requestId) {
        // 假设pollingAPI是一个通过requestId获取任务状态的异步函数
        return await pollingAPI(requestId);
      }
      return null;
    },
    {
      pollingInterval: 3000, // 每3秒轮询一次
      pollingWhenHidden: false, // 页面隐藏时不轮询
      manual: true, // 手动触发
      onSuccess: (result) => {
        if (result !== null) {
          // 停止轮询
          run.cancel();
        }
      },
    }
  );

  React.useEffect(() => {
    if (requestId) {
      run();
    }
  }, [requestId, run]);

  return (
    <div>
      <button onClick={submit}>提交</button>
      <div>任务状态: {data ? JSON.stringify(data) : "轮询中..."}</div>
    </div>
  );
};

export default ImgSelection;
